package com.lbd.gulimall.ware.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: linbd
 * @Description: feign远程调用会重新创建请求，丢失请求头。需要通过此拦截器，在发送请求前，将上一次请求的请求头信息设置到当前请求中
 * @Date: 2023/3/26 18:29
 */
@Configuration
@Slf4j
public class FeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //如果业务逻辑开启了异步处理，则RequestContextHolder的上下文无法在子线程共享（底层ThreadLocal存储，当前线程内才能共享）
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    if (request != null) {
                        String cookie = request.getHeader("Cookie");
                        template.header("Cookie", cookie);
                        log.info("为feign新创建的请求同步请求头信息");
                    }
                }else {
                    log.info("当前拦截的feign线程和主线程不是同一个线程。RequestContextHolder不共享");
                }
            }
        };
    }
}
